package com.report.socket;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.report.dto.response.MemberRes;
import com.report.dto.response.WebMemberRes;
import com.zmh.framework.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
 * @author summer
 * @date 2022-08-25 14:11
 */
@Component
@ServerEndpoint("/webSocket/{ticket}")
@Slf4j
@SaIgnore
public class WebSocketServer {

    private final static   Map<String, Session> clients = MapUtil.newConcurrentHashMap();


    public void remove(String equipmentId){
        if(clients.containsKey(equipmentId)){
            clients.remove(equipmentId);
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("ticket") String ticket){
         if(clients.containsKey(ticket)){
             clients.remove(ticket);
         }
          clients.put(ticket,session);
          log.info("onOpen:{}",session.getId());
    }


    @OnClose
    public void onClose(@PathParam("ticket") String ticket){
        remove(ticket);
    }

    @OnMessage
    public void onMessage(String message){
        log.info("onMessage:{}",message);
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        log.error("onError:{}",session.getId(),throwable);
    }


    public void sendMessage(WebMemberRes memberRes){
        try {
            Session session = clients.get(memberRes.getTicket());
            session.getBasicRemote().sendText(JSON.toJSONString(Result.successResult(memberRes)));
        } catch (IOException e) {
           log.error("error:{}",e.getMessage(),e);
        }
    }

    public void sendErrorMessage(String ticket){
        try {
            Session session = clients.get(ticket);
            session.getBasicRemote().sendText(JSON.toJSONString(Result.errorResult("微信绑定其他账号")));
        } catch (IOException e) {
            log.error("error:{}",e.getMessage(),e);
        }
    }
}
